/*
 * @Description: 
 * @Author: liks
 * @Date: 2025-01-06 11:07:12
 * @LastEditors: liks
 * @LastEditTime: 2025-01-06 16:59:03
 */
import { HttpException, Injectable } from '@nestjs/common';
import { CreateTagDto } from './dto/create-tag.dto';
import { UpdateTagDto } from './dto/update-tag.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Tag } from './entities/tag.entity';
import { PaginationService } from '../../common/pagination/pagination.service';

@Injectable()
export class TagService {
  constructor(
    @InjectRepository(Tag) private readonly tagRepository: Repository<Tag>,
    private pageService: PaginationService<Tag>,
  ) {
    this.pageService = new PaginationService<Tag>(this.tagRepository);
  }

  async create(createTagDto: CreateTagDto) {
    const data = this.tagRepository.create(createTagDto);
    return await this.tagRepository.save(data);
  }

  async findAll(params: {
    page: number;
    pageSize: number;
    name: string;
    keywords: string;
    sortFeild: string;
    sort: string;
  }) {
    const { page, pageSize, name, keywords, sortFeild, sort } = params;
    // 定义查询构造器
    const qb = this.tagRepository.createQueryBuilder('classification');
    // 模糊查询name、keywords
    name &&
      qb.andWhere('classification.name like :name', { name: `%${name}%` });
    keywords &&
      qb.andWhere('classification.keywords like :keywords', {
        keywords: `%${keywords}%`,
      });
    // 排序
    if (sortFeild && sort) {
      if (Reflect.ownKeys(new Tag()).includes(sortFeild)) {
        qb.orderBy(
          sortFeild,
          sort.toLocaleUpperCase().startsWith('ASC') ? 'ASC' : 'DESC',
        );
      } else {
        throw new HttpException(`不支持该字段:【${sortFeild}】进行排序`, 400);
      }
    }
    // console.log('pageSearch params', params);
    // 分页查询
    return this.pageService.pageSearch({
      page,
      pageSize,
      queryBuilder: qb,
    });
  }

  // 查询所有标签列表
  async findAllList() {
    return await this.tagRepository.find();
  }
  async findOne(id: string) {
    return await this.tagRepository.findOneBy({ id });
  }

  async update(id: string, updateTagDto: UpdateTagDto) {
    const data = await this.findOne(id);
    if (!data) throw new HttpException('数据不存在', 400);
    const updateData = this.tagRepository.merge(data, updateTagDto);
    return await this.tagRepository.save(updateData);
  }

  async remove(id: string) {
    const data = await this.findOne(id);
    if (!data) throw new HttpException('数据不存在', 400);
    return await this.tagRepository.delete({ id });
  }
}
